package com.jiayang.hhotel.util;


import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Base64;

import com.jiayang.hhotel.app.App;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;

public class IOUtil {

    public static Context getContext(){
        return App.getContext();
    }

    /*********************************
     * 本地缓存
     ***********************************/
    private final static String SP_NAME = "config";
    private static SharedPreferences sp;

    /**
     * 保存布尔值
     *
     * @param key
     * @param value
     */
    public static void saveBoolean(String key, boolean value) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().putBoolean(key, value).commit();
    }

    /**
     * 保存字符串
     *
     * @param key
     * @param value
     */
    public static void saveString(String key, String value) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        value = AESUtil.encrypt(key, value);
        sp.edit().putString(key + "_SB", value).commit();
    }

    public static void clear() {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().clear().commit();
    }

    /**
     * 保存long型
     *
     * @param key
     * @param value
     */
    public static void saveLong(String key, long value) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().putLong(key, value).commit();
    }

    /**
     * 保存int型
     *
     * @param key
     * @param value
     */
    public static void saveInt(String key, int value) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().putInt(key, value).commit();
    }

    /**
     * 保存float型
     *
     * @param key
     * @param value
     */
    public static void saveFloat(String key, float value) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);

        sp.edit().putFloat(key, value).commit();
    }

    /**
     * 删除缓存
     */
    public static void removeFinal(String key) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().remove(key + "_SB").commit();
    }

    public static void remove(String key) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        sp.edit().remove(key).commit();
    }

    /**
     * 获取字符值
     *
     * @param key
     * @param defValue
     * @return
     */
    public static String getString(String key, String defValue) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        String value = sp.getString(key + "_SB", defValue);
        if (value.equals(defValue)) {
            return defValue;
        } else {
            return AESUtil.decrypt(key, value);
        }
    }

    /**
     * 获取int值
     *
     * @param key
     * @param defValue
     * @return
     */
    public static int getInt(String key, int defValue) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        return sp.getInt(key, defValue);
    }

    /**
     * 获取long值
     *
     * @param key
     * @param defValue
     * @return
     */
    public static long getLong(String key, long defValue) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        return sp.getLong(key, defValue);
    }

    /**
     * 获取float值
     *
     * @param key
     * @param defValue
     * @return
     */
    public static float getFloat(String key, float defValue) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        return sp.getFloat(key, defValue);
    }

    /**
     * 获取布尔值
     *
     * @param key
     * @param defValue
     * @return
     */
    public static boolean getBoolean(String key, boolean defValue) {
        if (sp == null)
            sp = getContext().getSharedPreferences(SP_NAME, 0);
        return sp.getBoolean(key, defValue);
    }

    /**
     * 保存对象到本地(需要序列化)
     * @param key key
     * @param obj 对象
     */
    public static void saveObject(String key,Object obj){
        FileOutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            outputStream = getContext().openFileOutput(key,Context.MODE_PRIVATE);
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(obj);
            LogUtil.showLog("写入成功");
        } catch (IOException e) {
            LogUtil.showLog("写入失败");
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取本地对象
     * @param key key
     */
    public static Object getObject(String key){
        FileInputStream inputStream=null;
        ObjectInputStream objectinputStream=null;
        Object obj = null;
        try {
            inputStream = getContext().openFileInput(key);
            objectinputStream = new ObjectInputStream(inputStream);
            LogUtil.showLog("3");
            obj = objectinputStream.readObject();
        } catch (IOException e) {
            LogUtil.showLog("IOException="+e.toString()+"---"+e.getMessage());
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectinputStream!=null){
                try {
                    objectinputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file) {

        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // return size/1048576;
        return size;
    }

    /**
     * 转换文件大小
     *
     * @return
     */
    public static String formetFileSize(long file) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0M";
        if (file == 0) {
            return wrongSize;
        }
        if (file < 1024) {
            fileSizeString = df.format((double) file) + "B";
        } else if (file < 1048576) {
            fileSizeString = df.format((double) file / 1024) + "KB";
        } else if (file < 1073741824) {
            fileSizeString = df.format((double) file / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) file / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 删除文件
     */
    public static void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        } else {
        }
    }

    /**
     * 把数据写入文件
     *
     * @param is       数据流
     * @param path     文件路径
     * @param recreate 如果文件存在，是否需要删除重建
     * @return 是否写入成功
     */
    public static boolean writeFile(InputStream is, String path,
                                    boolean recreate) {
        boolean res = false;
        File f = new File(path);
        FileOutputStream fos = null;
        try {
            if (recreate && f.exists()) {
                f.delete();
            }
            if (!f.exists() && null != is) {
                File parentFile = new File(f.getParent());
                parentFile.mkdirs();
                int count = -1;
                byte[] buffer = new byte[1024];
                fos = new FileOutputStream(f);
                while ((count = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, count);
                }
                res = true;
            }
        } catch (Exception e) {
            LogUtil.showLog(e.toString());
        } finally {
            close(fos);
            close(is);
        }
        return res;
    }

    /**
     * 关闭流
     */
    public static boolean close(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                LogUtil.showLog(e.toString());
            }
        }
        return true;
    }

    /**
     * 判断sd卡是否存在
     *
     * @return
     */
    public static boolean ExistSDCard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }


    /**
     * 读取本地图片转换成bitmap
     *
     * @param uri 路径URl
     * @return
     */
    public static Bitmap SD2Bitmap(Uri uri) {
        Bitmap bit = null;
        try {
            File file = new File(uri.getPath());
            if (file.exists()) {
                bit = BitmapFactory.decodeFile(uri.getPath());
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return bit;
    }
}
